package com.example.springblog.controller;

import com.example.springblog.constant.Constants;
import com.example.springblog.model.BlogInfo;
import com.example.springblog.model.BlogList;
import com.example.springblog.service.BlogService;
import com.example.springblog.utils.JwyUtils;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RequestMapping("/blog")
@Slf4j
@RestController
public class BlogController {
    @Autowired
    private BlogService blogService;
    @RequestMapping("/getList")
    public List<BlogList> getList(){
        log.info("获取博客列表");
        return blogService.getList();
    }
    @RequestMapping("/getBlogDetail")
    public BlogInfo getBlogDetail(Integer blogId, HttpServletRequest request){
        log.info("getBlogDetail, blogId+{}",blogId);
        BlogInfo blogInfo= blogService.getBlogDetail(blogId);
        String token=request.getHeader(Constants.REQUEST_HEADER_TOKEN);
        Integer userId=JwyUtils.getIdByToken(token);
        if(userId!=null&&userId==blogInfo.getUserId()){
            blogInfo.setLoginUser(true);
        }else {
            blogInfo.setLoginUser(false);
        }
        return blogInfo;
    }
    @RequestMapping("/add")
    public Boolean addBook(BlogInfo blogInfo,HttpServletRequest request){
    log.info("添加图书,blogInfo.getTitle{}",blogInfo.getTitle());
    log.info("添加图书,blogInfo.getContent{}",blogInfo.getContent());
    if(!StringUtils.hasLength(blogInfo.getContent())||!StringUtils.hasLength(blogInfo.getTitle())){
        return false;
    }
    String token=request.getHeader(Constants.REQUEST_HEADER_TOKEN);
    Integer userId=JwyUtils.getIdByToken(token);
    if(userId==null||userId<0){
        return false;
    }
    blogInfo.setUserId(userId);
    return blogService.insertBlog(blogInfo);
    }
    @RequestMapping("/update")
    public Boolean update(BlogInfo blogInfo){
        log.info("更新博客");
        if (blogInfo.getId()==null
                || !StringUtils.hasLength(blogInfo.getTitle())
                || !StringUtils.hasLength(blogInfo.getContent())){
            return false;
        }
        blogService.update(blogInfo);
        return true;
    }
    @RequestMapping("/delete")
    public Boolean delete(Integer blogId){
        log.info("删除博客, blogId:{}", blogId);
        if (blogId<=0){
            return false;
        }
        BlogInfo blogInfo = new BlogInfo();
        blogInfo.setId(blogId);
        blogInfo.setDeleteFlag(1); //删除
        blogService.update(blogInfo);
        return true;
    }


}
